﻿using System;
using System.Web.Services;
using ControleRepresentante.Data.Catalogs;
using ControleRepresentante.Logic.Models;
using ControleRepresentante.Logic.Repositories;

namespace WebSite.Services
{
    public class WebServiceBase : WebService
    {
        private IRepositoryProvider m_RepositoryProvider;

        protected IRepositoryProvider RepositoryProvider
        {
            get
            {
                if (m_RepositoryProvider == null)
                {
                    RepositoryProviderConfiguration repositoryProviderConfiguration = new RepositoryProviderConfiguration(
                        () => Session["UserInfo"] as UserInfo,
                        () => Session["RepresentanteId"] as Guid?);

                    RepositoryProvider<ControleRepresentanteCatalog> repositoryProvider = new RepositoryProvider<ControleRepresentanteCatalog>(repositoryProviderConfiguration);
                    ControleRepresentante.Logic.Repositories.RepositoryProvider.RegisterControleRepresentanteRepositories(repositoryProvider);

                    m_RepositoryProvider = repositoryProvider;
                }
                return m_RepositoryProvider;
            }
        }

        [WebMethod(EnableSession = true)]
        public void Logout()
        {
            Session.Abandon();
        }

        [WebMethod(EnableSession = true)]
        public bool Login(string username, string password)
        {
            if (Session["UserInfo"] != null)
            {
                return true;
            }
            IUserRepository userRepository = RepositoryProvider.GetRepository<IUserRepository>();
            Representante representante;
            User user = userRepository.GetUser(username, password, out representante);
            if (user == null || user.IsAdmin || !user.Ativo || representante == null || !representante.Ativo || !representante.UseJolitex || !user.HasPermission(Area.Sync, Operacao.Synchronize))
            {
                return false;
            }
            Session["UserInfo"] = new UserInfo(user);
            Session["RepresentanteId"] = representante.Id;
            return true;
        }
    }
}